<script setup lang="ts">
import { Table } from '@/models/reactiveComponent';
import { computed, ref, inject, watch } from 'vue'
import * as cpUtils from './utils';
import Error from "./Error.vue";
import * as injectKeys from "@/services/injectKeys";

const props = defineProps<{ model: Table }>()
const model = props.model

const datasetServices = inject(injectKeys.datasetKey)!
const sqlServices = inject(injectKeys.sqlAnalyzeKey)!
const dbServices = inject(injectKeys.dbKey)!


const filterUtils = cpUtils.getFilterUtils(model, {
    dataset: datasetServices,
    sqlAnalyze: sqlServices,
    db: dbServices,
})

const data = filterUtils.getData()

const tableData = computed(() => data.value.rows)
const columns = computed(() => data.value.fields)
// const totalRows = computed(() => tableData.value.length)

let tableBaseHeight = 30
if (tableData.value.length <= 10) {
    tableBaseHeight = tableData.value.length * 4
}

const tableHeight = `${tableBaseHeight}em`
const tableBoxHeight = `${tableBaseHeight + 1}em`

const currentPage = ref(1)
const withPages = computed(() => {
    const size = 10
    const start = (currentPage.value - 1) * size
    const end = start + size

    return tableData.value.slice(start, end)
})




const currentRow = ref()

const handleCurrentChange = (val: any | undefined) => {
    currentRow.value = val
}



// function onCurrentChange() {

// }

watch(columns, col => {
    // console.log(col);

})

</script>

<template>
    <div class="bi-table" :data-tag="model.tag">
        <Error>
            <div style="display: flex;max-width: 100%;">

                <div class="table-fix">
                    <el-table class="table" :height="tableHeight" header-row-class-name="table-header" border
                        :data="withPages" stripe max-height="35rem" style="width: 100%"
                        @current-change="handleCurrentChange">
                        <el-table-column show-overflow-tooltip v-for="col in columns" :property="col" :label="col" />

                    </el-table>

                    <el-pagination hide-on-single-page background layout="prev, pager, next" :total="tableData.length"
                        v-model:current-page="currentPage" :page-size="10">
                    </el-pagination>
                </div>

            </div>

        </Error>

    </div>
</template>

<style scoped lang="less">
.bi-table {
    overflow: auto;
    height: v-bind(tableBoxHeight);

    .table-fix {
        flex: 1;
        min-width: 30rem;
    }

    .table {
        margin-bottom: 2rem;
    }

    :deep(.table-header) th {
        font-size: 1.1em;
        font-weight: bold;

        background-color: rgba(143, 225, 253, 0.085);
    }
}
</style>